<?php
/**
 * User: Kris
 * Date: 1/17/12
 */

require_once APPPATH . 'core/controller.php';

class ChannelController extends Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->load->library('form_validation');
        $this->data['styles'][] = '/public/css/category.css';
    }

    public function view($channelName)
    {
        $topThree = new TopThreePosts();
        $latestPosts = null;


        $channel = $this->em->getRepository('Channel')->findOneBy(array('name' => str_replace('_', ',',str_replace('-', ' ', $channelName))));

        if (sizeof($channel) != 0)
        {
            $posts = $this->em->createQuery("SELECT p FROM Post p JOIN p.channels c WHERE c.id = :channelId ORDER BY p.id DESC")->setMaxResults(12);
            $posts->setParameter('channelId', $channel->getId());
            $latestPosts = $posts->getResult();

            /**
             * @var $user User
             */
            $user = $this->em->find('User', $this->session->userdata('userId'));

            $this->data['userIsSubscribed'] = false;
            if($user != null && $channel != null)
            {
                $this->data['userIsSubscribed'] = $user->getChannelSubscriptions()->contains($channel);
            }


            foreach ($latestPosts as $post) {
                $topThree->validateAndAdd($post);
            }

            $this->data['topThree'] = $topThree->getTopThree();
            $this->data['latestPosts'] = $latestPosts;
            $this->data['channel'] = $channel;
        }

        $this->parser->parse("channel/view.tpl", $this->data);
    }

    public function create()
    {
        $query = $this->em->createQuery("SELECT c FROM Channel c JOIN c.owner u WHERE u.id = :userId");
        $query->setParameter('userId', $this->session->userdata('userId'));

        $channels = $query->getResult();
        $this->data['channels'] = $channels;
        $this->data['styles'][] = "/public/css/frontpage-index.css";

        //$this->em->getRepository('Channel')->findOneBy(array('name' => "test"));
        $this->parser->parse("channel/create.tpl", $this->data);
    }

    public function insert()
    {
        $this->form_validation->set_rules('name', 'Naam', 'required');
        $this->form_validation->set_error_delimiters('', '');
        $this->form_validation->set_message('required', "Een naam dient ingevoerd te worden");

        if ($this->form_validation->run() == FALSE)
        {
            $this->create();
        }
        else
        {
            $this->form_validation->set_rules('name', 'Naam', 'callback_name_exist');
            $this->form_validation->set_error_delimiters('', '');
            $this->form_validation->set_message('name_exist', $this->input->post('name') . " is niet beschikbaar");

            if ($this->form_validation->run() == FALSE)
            {
                $this->create();
            }
            else
            {
                $this->createChannel();
            }
        }
    }

    public function name_exist($string)
    {
        return $this->em->getRepository('Channel')->findOneBy(array('name' => $string)) == null;
    }

    private function createChannel()
    {
        $user = $this->em->find('User', $this->session->userdata('userId'));

        $name = $this->input->post('name');
        $channel = new Channel();
        $channel->setName($name);
        $channel->setOwner($user);

        $this->em->persist($channel);
        $this->em->flush();

        redirect("channel/create", "location");
    }
}